<style>
    .layui-form-label {
        width: 100px;
    }
    .layui-input-block {
        margin-left: 130px;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">名称：</label>
                                    <div class="layui-input-inline">
                                        <input name="name" class="layui-input" type="text" placeholder="分类名"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" layui-form-keyDownSearch="true" lay-submit>查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                                </div>
                            </div>
                            <div class="query-rt"></div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="productCategoryBtnAdd" class="layui-btn icon-btn color-reseda">添加分类</button>
                        </div>
                        <div class="lay-btn-rt">

                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="productCategoryTable" lay-filter="productCategoryTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="productCategoryTableBar">
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">修改</a>
    {{# if(!d.isFinal){  }}
    <a class="layui-btn layui-btn-xs" lay-event="addSub">添加子分类</a>
    {{# } }}
    {{# if(!d.hasChild){ }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    {{# } }}
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="productCategoryForm">
    <form lay-filter="productCategoryForm" class="layui-form model-form">
        <input name="id" type="hidden"/>

        <div class="layui-form-item" id="PID">
            <label class="layui-form-label">所属分类</label>
            <input name="parentId" type="hidden"/>
            <div class="layui-input-block" id="selectCategory" lay-filter="selectCategory">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">分类名</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入名称" type="text" class="layui-input" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">适用主体类型</label>
            <div class="layui-input-block">
                <select name="type" id="type1" lay-verify="required">
                    <option value="">请选择主体类型</option>
                    <option value="supplier">供应商</option>
                    <option value="client">客户</option>
                    <option value="staff">员工</option>
                    <option value="channel">渠道</option>
                    <option value="shareholder">股东</option>
                    <option value="other">其他</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item" >
            <label class="layui-form-label">描述</label>
            <div class="layui-input-block">
                <textarea id="remark" name="remark" placeholder="请输入描述" class="layui-textarea" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否终极分类</label>
            <div class="layui-input-block">
                <input name="isFinal" type="checkbox" lay-skin="switch" value="1"  lay-text="终极分类|非终极分类"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否启用</label>
            <div class="layui-input-block">
                <input name="isDeleted" type="checkbox" lay-skin="switch" value="1" checked="false" lay-text="启用|停用"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">排序</label>
            <div class="layui-input-block">
                <input name="sortNumber" placeholder="请输入排序" type="text" class="layui-input" lay-verify="" required/>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="productCategoryFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<script type="text/html" id="childForm">
    <form lay-filter="productCategoryForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <input name="parentId" type="hidden"/>


        <div class="layui-form-item">
            <label class="layui-form-label">分类名</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入名称" type="text" class="layui-input" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">适用主体类型</label>
            <div class="layui-input-block">
                <select name="type" id="type" lay-verify="required">
                    <option value="">请选择主体类型</option>
                    <option value="supplier">供应商</option>
                    <option value="client">客户</option>
                    <option value="staff">员工</option>
                    <option value="channel">渠道</option>
                    <option value="shareholder">股东</option>
                    <option value="other">其他</option>

                </select>
            </div>
        </div>
        <div class="layui-form-item" >
            <label class="layui-form-label">描述</label>
            <div class="layui-input-block">
                <textarea  name="remark" placeholder="请输入描述" class="layui-textarea" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否终极分类</label>
            <div class="layui-input-block">
                <input name="isFinal" type="checkbox" lay-skin="switch" value="1"  lay-text="终极分类|非终极分类"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否启用</label>
            <div class="layui-input-block">
                <input name="isDeleted" type="checkbox" lay-skin="switch" value="1" checked="false" lay-text="启用|停用"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">排序</label>
            <div class="layui-input-block">
                <input name="sortNumber" placeholder="请输入排序" type="text" class="layui-input" lay-verify="" required/>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="childFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'laydate', 'admin' ,'laytpl','tableTreeDj', 'config','tree'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var laydate = layui.laydate;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var laytpl = layui.laytpl;
        var tableTree = layui.tableTreeDj;
        var tree = layui.tree;


        // 渲染表格
        var insTb = tableTree.render({
            id: '#productCategoryTable',
            elem: '#productCategoryTable',
            url: config.base + 'enterprise/contract/admin/contractCategory/list?limit=9999',
            toolbar: true,
            defaultToolbar: ["filter"],
            page: false,
            cellMinWidth: 100,
            cols: [[
                {type: 'checkbox'}
                // ,{field: 'id', sort: true, title: 'ID'}
                ,{type: 'numbers', title: '序号'}
                ,{field: 'name', sort: true, title: '分类名'}
                ,{field: 'typeDesc', sort: true, title: '面向主体类型'}
                ,{field: 'remark', sort: true, title: '描述'}

                ,{field: 'createTime', sort: true, title: '创建时间'}
                ,{field: 'creatorName', sort: true, title: '创建人'}
                ,{field: 'sortNumber', sort: true, title: '排序'}
                ,{field: 'isDeleted', sort: true, title: '状态',templet:function (d) {
                        if(d.hasEnableChild){
                            if(d.isDeleted){
                                return '<input name="isDeleted" type="checkbox" lay-skin="switch" value="'+d.id+'" checked="'+d.isDeleted+'" lay-filter="isDeleted"  lay-text="启用|停用" disabled/>';
                            }else{
                                return '<input name="isDeleted" type="checkbox" lay-skin="switch" value="'+d.id+'" lay-filter="isDeleted"   lay-text="启用|停用"/>';
                            }
                        }else{
                            if(d.isDeleted){
                                return '<input name="isDeleted" type="checkbox" lay-skin="switch" value="'+d.id+'" checked="'+d.isDeleted+'" lay-filter="isDeleted"  lay-text="启用|停用"/>';
                            }else{
                                return '<input name="isDeleted" type="checkbox" lay-skin="switch" value="'+d.id+'" lay-filter="isDeleted"   lay-text="启用|停用"/>';
                            }
                        }


                    }}
                ,{align: 'center', toolbar: '#productCategoryTableBar', title: '操作', width: 300}
            ]],
            done: function (res, curr, count) {
                //移除按钮
                var menuButton = config.getMenuButton(location.hash);
                if(menuButton.indexOf("搜索") == -1){
                    $('.layui-form.toolbar').remove();
                }
                if(menuButton.indexOf("修改") == -1){
                    $("[lay-event='edit']").remove();
                }
                if(menuButton.indexOf("删除") == -1){
                    $("[lay-event='del']").remove();
                }
            }
        }, {keyPid: "parentId", title: "name"});

        // 工具条点击事件
        table.on('tool(productCategoryTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //修改
                showEditModel(data,'productCategoryForm','productCategoryFormSubmit');
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            }else if (obj.event === 'addSub') {
                //添加子级分类
                showEditModel(data, 'childForm', 'childFormSubmit', data.id);
            }
        });

        //监听排序
        table.on('sort(productCategoryTable)', function(obj){
            table.reload('productCategoryTable', {
                initSort: obj
                ,where: {
                    sort: obj.field
                    ,order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field,page: {curr: 1}},'data');
        });
        // 重置搜索
        form.on('submit(resets)', function (data) {
            $(".lay-header").find('select').val("");
            $(".lay-header").find('input').val("");
            let field = data.field;
            for (let key in field) {
                field[key] = ''
            }
            insTb.reload({where: field, page: {curr: 1}}, 'data');
        });

        form.on('switch(isDeleted)',function(obj){
            if(obj.elem.checked){
                enable(obj.value)
            }else{
                disable(obj.value)
            }
        })

        function enable(id){
            admin.req('enterprise/contract/admin/contractCategory/enable', {id:id}, function (res) {
                if (res.code == 200) {
                    layer.msg(res.msg, {icon: 1});
                    insTb.reload('productCategoryTable');
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, 'POST');
        }

        function disable(id){
            admin.req('enterprise/contract/admin/contractCategory/disable', {id:id}, function (res) {
                if (res.code == 200) {
                    layer.msg(res.msg, {icon: 1});
                    insTb.reload('productCategoryTable');
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, 'POST');
        }

        // 添加按钮点击事件
        $('#productCategoryBtnAdd').click(function () {
            showEditModel(undefined, 'productCategoryForm', 'productCategoryFormSubmit');
        });

        // 显示编辑弹窗
        function showEditModel(data, formId, submitButton, parentIdVal) {
            let finalCategoryIds = [];
            //加载终极分类
            admin.req('enterprise/contract/admin/contractCategory/list', {limit:9999}, function (res) {
                if (res.code == 200) {
                    if (res.data != null) {
                        for (let i = 0; i < res.data.length; i++) {
                            if (res.data[i].isFinal=='yes'){
                                finalCategoryIds.push(res.data[i].id)
                            }
                        }
                    }
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, 'get', false);
            admin.open({
                type: 1,
                area: '660px',
                offset: '65px',
                title: parentIdVal ? '添加子分类' : (data ? '编辑分类' : '添加分类'),
                content: $('#' + formId).html(),
                success: function () {
                    function treeEach(treeData, ids) {
                        $.each(treeData, function (i, val) {
                            if (customContains(ids, val.value)) {
                                val.disabled = true;
                            }
                            if (val.children && val.children.length > 0) {
                                treeEach(val.children, ids);
                            }
                        });
                    }

                    let customContains = function (box, val) {
                        for (let i = 0; i < box.length; i++) {
                            if (box[i] == val) {
                                return true;
                            }
                        }
                        return false;
                    };

                    //根据父id选择主体类型（添加子分类）
                    if (parentIdVal){
                        admin.req('enterprise/contract/admin/contractCategory/list', {limit:9999,id:parentIdVal}, function (res) {
                            var data = res.data[0];
                            if (data){
                                let select = 'dd[lay-value=' + data.type + ']';
                                $('#type').siblings("div.layui-form-select").find('dl').find(select).click();
                                //**设置禁止选择：**//
                                $("#type").attr("disabled", "disabled");
                                form.render("select");
                            }

                        },'get')
                    }

                    //**设置修改时主体类型禁止选择：**//
                    if (data){
                        $("#type1").attr("disabled", "disabled");
                        form.render("select");
                    }


                    if (formId != 'childForm') {
                        xmSelect.render({
                            el: '#selectCategory',
                            model: {label: {type: 'text'}},
                            radio: true,
                            clickClose: true,
                            filterable: true,
                            tree: {
                                show: true,
                                strict: false,
                                expandedKeys: [-1],
                            },
                            tips: '顶级分类',
                            height: 'auto',
                            data() {
                                if (parentIdVal != undefined) {
                                    $("input[name='parentId']").val(parentIdVal);
                                }

                                let treeData = tableTree.getTree(data && parentIdVal == undefined ? data.parentId : parentIdVal, data ? data.id : null);
                                if (finalCategoryIds != null && finalCategoryIds.length > 0) {
                                    treeEach(treeData, finalCategoryIds);
                                }
                                return treeData;
                            },
                            on: function (data) {
                                //被选中的select的id,如果没有 -1
                                let parentId = data.arr.length > 0 ? data.change[0].value : -1;
                                $("input[name='parentId']").val(parentId);

                                //移除禁止选择，让主体类型可以进行选中
                                $("#type1").removeAttr("disabled");
                                form.render('select');

                                console.log("选中分类的id："+data.change[0].value);
                                if (parentId!=-1){
                                    var changeId = data.change[0].value;
                                    admin.req('enterprise/contract/admin/contractCategory/list', {limit:9999,id:changeId}, function (res) {
                                        var data = res.data[0];
                                        if (data){
                                            let select = 'dd[lay-value=' + data.type + ']';
                                            $('#type1').siblings("div.layui-form-select").find('dl').find(select).click();

                                            //主体类型选中，设置禁止
                                            $("#type1").attr("disabled", "disabled");
                                            form.render("select");
                                        }

                                    },'get');
                                }

                            },
                        });

                    }
                    //data 非空取值names
                    if (!config.isEmptyObject(data)) {
                        data.name = data.name.indexOf("</span>") > 0 ? data.name.split("</span>")[1] : data.name;
                        data.name = data.name.indexOf("&nbsp; &nbsp;") > 0 ? data.name.split(" &nbsp; &nbsp;").length>2?data.name.split(" &nbsp; &nbsp;")[2]:data.name.split(" &nbsp; &nbsp;")[1] : data.name;
                    }

                    //添加子级渲染所属分类
                    if (formId == 'childForm') {
                        data.code= '';
                        data.name = '';
                        data.description = '';
                        data.status='';
                        form.val(formId, data);
                        $("form input[name='parentId']").val(data.id);
                        data = undefined;
                    }

                    if (data){
                        var option = $("form select[name='isFinal']").find("option");
                        layui.each(option, function(index, item){
                            if(data.isFinal  == item.text){
                                data.isFinal = item.value;
                            }
                        });
                    }



                    form.val('productCategoryForm', data);


                    // 表单提交事件
                    form.on('submit('+submitButton+')', function (d) {
                        layer.load(2);
                        if(d.field.parentId==null||d.field.parentId==''){
                            d.field.parentId=-1
                        }
                        var isDeleted=$("form input[name='isDeleted']").prop("checked");
                        if(!isDeleted){
                            d.field.isDeleted=false;
                        }else{
                            d.field.isDeleted=true;
                        }
                        var isFinal=$("form input[name='isFinal']").prop("checked");
                        if(!isFinal){
                            d.field.isFinal=false;
                        }else{
                            d.field.isFinal=true;
                        }
                        admin.req(data ? 'enterprise/contract/admin/contractCategory/update' : 'enterprise/contract/admin/contractCategory/add', d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                insTb.reload('productCategoryTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('enterprise/contract/admin/contractCategory/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                        insTb.reload('productCategoryTable');
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }

        // 导出excel
        $('#productCategoryBtnExport').click(function () {
            var checkRows = table.checkStatus('productCategoryTable');
            if (checkRows.data.length == 0) {
                layer.msg('请选择要导出的数据', {icon: 2});
            } else {
                table.exportFile(insTb.config.id, checkRows.data, 'xls');
            }
        });

    });
</script>